package com.xingdata.jjxc.pushnavi;

import android.util.Log;

import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.io.*;

public class UdpClient {
  private String remoteHost="192.168.43.1";
  private int remotePort=18944;
  private DatagramSocket socket;
  ClientThread thread;
  String Tag = "UdpClient";

  public UdpClient()throws IOException{
     socket = new DatagramSocket(); //
     thread = new ClientThread();
     thread.start();
//     go();
  }
  
  public static void main(String args[])throws IOException{
     new UdpClient();
  }
  
  public static List<ProtoMsg> msgQueue= new ArrayList<ProtoMsg>();
  
  Object sync = new Object();
  class ClientThread extends Thread{
	  boolean isRunning = false;
	  public ClientThread(){
		  isRunning = true;
	  }
	  
	  public void startThread(){
		  isRunning = true;
	  }
	  
	  public void stopThread(){
		  isRunning =false;
		  msgQueue.clear();
		  interrupt();
	  }
	  
	  @Override
	  public void run() {
		  try{
		      byte[] outputData = new byte[1];
		      InetAddress remoteIP=InetAddress.getByName(remoteHost);
		      DatagramPacket outputPacket = new DatagramPacket(outputData,
									  outputData.length,
									  remoteIP,
									  remotePort);
		      while(isRunning && !isInterrupted()){
//		    	  Log.e(Tag,"client Udp thread runnning....");
		    	  if(msgQueue.size() > 0){
			        ProtoMsg protmsg = msgQueue.get(0);
			        outputData = ProtoMsg.toJsonString(protmsg).getBytes();
			        outputPacket.setData(outputData);
			        outputPacket.setLength(outputData.length);
			        socket.send(outputPacket);  // Server ������ݱ�
			        msgQueue.remove(0);
		    	  }else{
		    		  try {
		    			  Thread.sleep(3000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		    	  }
		       }
		    }catch(IOException e){
		       e.printStackTrace();
		    }finally{
		       socket.close();
		    }
	  }
  }
  
  public void enqueueMsg(ProtoMsg msg){
	  msgQueue.add(msg);
  }
  
//  void go(){
//	  NaviParams param = new NaviParams();
//      param.selectedIndex = 3;
//      param.start = new MyLatLng(111.22,33.44);
//      param.dest =  new MyLatLng(666.22,999.99);
//      param.waypoints.add(new MyLatLng(555.22,777.99));
//      param.waypoints.add(new MyLatLng(555.22,777.99));
//      param.waypoints.add(new MyLatLng(555.22,777.99));
//      param.waypoints.add(new MyLatLng(555.22,777.99));
//      ProtoMsg msg = new ProtoMsg("startNavi",param.toJsonString());
//      msgQueue.add(msg);
//  }
}  
